#!/bin/bash - 
#===============================================================================
#          FILE:  gen_linkSyms.sh
#         USAGE:  ./gen_linkSyms.sh 
export  LC_ALL=C
argc=$#
# echo argc=${argc}

if [ $argc != 1 ]
then
    echo argc=${argc} error, exit
    exit -1
fi
elf=$1
if ! [ -f $elf ]
then
    echo "file:${elf} don't,exit"
    exit -2
fi
is_elf_match=`file ${elf} | sed -n -e "s:.* \(ELF\) .*:\1:gp"`
# echo ${is_elf_match}
if [ "${is_elf_match}" != "ELF" ]
then
    ar_file_key="${elf}: current ar archive"
    is_ar_match=`file ${elf}`
    if [ "${ar_file_key}" != "${is_ar_match}" ]
    then
        echo file:${elf} format is not elf,exit
        exit -3
    fi
fi


echo "/* This file is generated by specific tool, please don't modify it */"
echo '#include "libSym.h"'
echo ''

${CROSS_COMPILE}nm -Ag ${elf} | \
    grep " [DdBbT] " | \
    awk '{print $2,$3}' | \
    sed -n -f sym_filter.sed | \
    awk '{print $1,$2}' | sort -uf > tmp_declare.txt 


while read t sym
do 
    # echo type=${t},sym=${sym}
    case ${t} in
        "b"|"B"|"d"|"D")
            echo "extern int ${sym}[];" ;;
        "T"|"t")
            echo "extern void * ${sym}(void);" ;;
    esac; 

done < tmp_declare.txt

echo ""
echo "static const TsymPara g_symTbl[] ="
echo "{"

${CROSS_COMPILE}nm -Ag ${elf} | \
    grep " [DdBbT] " | \
    awk '{print $2,$3}' | \
    sed -n -f sym_filter.sed | \
    awk '{print $2,$1}' | sort -u > tmp_array.txt

while read sym t
do 
    # echo type=${t},sym=${sym}
    sym_name=\"${sym}\"
    case ${t} in
        "d"|"D")
            printf "    {%-32s, SYM_TYPE_D, %s},\n" "${sym_name}" ${sym};;
        "b"|"B")
            printf "    {%-32s, SYM_TYPE_B, %s},\n" "${sym_name}" ${sym};;
        "T"|"t")
            # {"xrealloc"                      , SYM_TYPE_T, xrealloc},
            printf "    {%-32s, SYM_TYPE_T, %s},\n" "${sym_name}" ${sym};;
    esac; 

done < tmp_array.txt

rm -rf tmp_declare.txt
rm -rf tmp_array.txt

echo "};"

echo ''
echo ''
echo 'int usrSymInit(void)'
echo '{'
echo '    return sysSymTblAdd(g_symTbl, ARRAY_SIZE(g_symTbl));'
echo '}'
